package app.controllers.api.app;

import app.Const;
import app.models.basic.RiskModel;
import app.models.basic.RiskOptions;
import app.models.basic.RiskProblem;
import app.models.member.Member;
import app.services.auth.AuthInterceptor;
import app.services.auth.AuthParam;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.Restful;
import goja.Func;
import goja.StringPool;
import goja.mvc.Controller;

import java.util.List;

/**
 * <p>
 * The url app/risk Controller.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
@Before({Restful.class, AuthInterceptor.class})
public class RiskController extends Controller {

    /**
     * The index route.
     * the url /app/risk
     */
    @AuthParam(auth = true)
    public void index() {
        renderNull();
    }


    @AuthParam(auth = true)
    public void save() {
        String data = getPara(Const.PARAM_DATA);

        List<String> answers = Func.COMMA_SPLITTER.splitToList(data);
        int total = 0;
        for (String answer : answers) {
            RiskOptions options = RiskOptions.dao.findById(answer);
            int score = options.getNumber("score").intValue();
            total = total + score;
        }
        final String category = getPara("category");
        List<RiskModel> models = RiskModel.dao.findByCategory(category);

        String risk_level = null;

        for (RiskModel model : models) {
            if (model.getNumber("min_score").intValue() < total || total < model.getNumber("max_score").intValue()) {
                risk_level = model.getStr("risk_level");
                break;
            }
        }
        Member member = getAttr(AuthInterceptor.ATTR_MEMBER);
        if (!Strings.isNullOrEmpty(risk_level)) {

            member.set(Const.FIELD_RISK_TOLERANCE, risk_level);
            member.update();
        }
        renderAjaxSuccess(member);

    }

    @AuthParam(auth = true)
    public void show() {

        final String category = getPara();
        List<RiskProblem> problems = RiskProblem.dao.findByCategory(category);
        for (RiskProblem problem : problems) {
            List<RiskOptions> optionses = RiskOptions.dao.findByProblem(problem.getNumber(StringPool.PK_COLUMN).intValue());
            problem.put("optionses", optionses);
        }

        renderAjaxSuccess(problems);
    }
}